// pages/equity/equity.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentNum:1,
    isAllChecked:false,
    userId:'',
    phone:'',
    totalPrice:'',
    totalOriPrice:'',
    orinDiscount:'',
    buyCarLists:[
     
    ],
  },

 //获取商品列表
 getCarList:function(){
  let _this=this;
  wx.request({
    url:app.globalData.onlineUrl+"/getBuyCarList",
    header:{'content-type': 'application/json'},
    method:"POST",
    data:{phone:_this.data.phone},
    dataType:"json",
    complete:function(result) {
      console.log(5674556,result.data.data);
      let data=result.data.data;
      _this.setData({
        buyCarLists:data,
      })
      _this.calculateTotalPrice()
    }
  })
},

settlement:function(e){
  const arry = this.data.buyCarLists.filter(item => item.isSelected && item.state!=0 && item.inventory>0);
  const items ={
    totalPrice:this.data.totalPrice,
    totalOriPrice:this.data.totalOriPrice,
    orinDiscount:this.data.orinDiscount,
    items:arry
  }
  console.log(123,items)
  wx.navigateTo({
    url: '/pages/settlement/settlement?item='+JSON.stringify(items)
  })
},
  coupon() {
    wx.navigateTo({
      url: '/pages/coupon/coupon'
    })
  },
  checkPro:function(e){
    let index=e.currentTarget.dataset.index;
    console.log(567,this.data.buyCarLists[`${index}`].isSelected)
    this.setData({
      ['buyCarLists['+ index + '].isSelected'] : !this.data.buyCarLists[`${index}`].isSelected
    });
    this.upCarById(this.data.buyCarLists[`${index}`].id,this.data.buyCarLists[`${index}`].buyNum,this.data.buyCarLists[`${index}`].isSelected);
    this.calculateTotalPrice()
  },
  toggleCheck: function() {
    this.data.buyCarLists.forEach(item => {
      item.isSelected = !this.data.isAllChecked;
    });
    this.setData({
      buyCarLists:this.data.buyCarLists,
      isAllChecked: !this.data.isAllChecked // 切换状态
    });
    this.calculateTotalPrice()
  },
  //计算总价
  calculateTotalPrice: function() {
    const totalPrice = this.data.buyCarLists.filter(item=>item.isSelected==1 && item.state!=0 && item.inventory>0).reduce((accumulator,item)=>accumulator+item.price*item.buyNum,0);
    const totalOriPrice = this.data.buyCarLists.filter(item=>item.isSelected==1 && item.state!=0 && item.inventory>0).reduce((accumulator,item)=>accumulator+item.orinprice*item.buyNum,0);
    // 更新页面数据以显示总价
    this.setData({
      totalPrice: totalPrice.toFixed(2),
      totalOriPrice: totalOriPrice.toFixed(2),
      orinDiscount: (totalOriPrice-totalPrice).toFixed(2)
    });
  },
 // 增加数量
 increaseQuantity(e) {
  let index=e.currentTarget.dataset.index;
  let buyNum=this.data.buyCarLists[`${index}`].buyNum;
  let inventory=this.data.buyCarLists[`${index}`].inventory;
  console.log(888,buyNum)
  if(buyNum<inventory){
    buyNum++
    this.setData({
      ['buyCarLists['+ index + '].buyNum'] : buyNum
    });
    this.upCarById(this.data.buyCarLists[`${index}`].id,this.data.buyCarLists[`${index}`].buyNum,this.data.buyCarLists[`${index}`].isSelected);
    this.calculateTotalPrice()
  }
},
//2.0跳转商品详情
gotoProductDetail:function(e){
  wx.navigateTo({
    url: '/pages/productDetails/productDetails?id='+e.currentTarget.dataset.proid
  })
},
// 减少数量
decreaseQuantity(e) {
  let index=e.currentTarget.dataset.index;
  let buyNum=this.data.buyCarLists[`${index}`].buyNum;
  console.log(777,buyNum)
  if(buyNum>1){
    buyNum--;
    this.setData({
      ['buyCarLists['+ index + '].buyNum'] : buyNum
    });
    this.upCarById(this.data.buyCarLists[`${index}`].id,this.data.buyCarLists[`${index}`].buyNum,this.data.buyCarLists[`${index}`].isSelected);
  }else{
    let this_=this;
    wx.showModal({
      title: '提示',
      content: '确定要删除此商品吗？',
      success: function(res) {
        if (res.confirm) {
          this_.delCarById(this_.data.buyCarLists[`${index}`].id);
          this_.data.buyCarLists.splice(index, 1);
          this_.setData({
            buyCarLists: this_.data.buyCarLists
          });
          
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  }
  this.calculateTotalPrice()
},
delCarById:function(id){
  let _this=this;
  wx.request({
    url:app.globalData.onlineUrl+"/delBuyCar",
    header:{'content-type': 'application/json'},
    method:"POST",
    data:{id:id},
    dataType:"json",
    complete:function(result) {
      console.log(33,result.data.data);
      app.getBuyCarNum();
    }
  })
},
upCarById:function(id,buyNum,isSelected){
  let _this=this;
  wx.request({
    url:app.globalData.onlineUrl+"/upBuyCar",
    header:{'content-type': 'application/json'},
    method:"POST",
    data:{
      id:id,
      buyNum:buyNum,
      isSelected:isSelected
    },
    dataType:"json",
    complete:function(result) {
      console.log(33,result.data.data);
    }
  })
},
setNUm:function(){
 
},
  detail:function(e){
    wx.navigateTo({
      url: '/pages/productDetails/productDetails?id='+e.currentTarget.dataset.id
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    app.getBuyCarNum()
    wx.showShareMenu({
      withShareTicket: true
    })
    this.getTabBar().setData({
      PageCur: 'equity'
    })
    this.setData({
      phone:wx.getStorageSync('phone'),
      userId:wx.getStorageSync('userId')
    })
    this.getCarList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
/**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    console.log(12242);
    return {
      title: '来伊份零食会员权益',
      path: 'pages/index/index',
      imageUrl: '/images/share.png'
    }
  }
})